// 通常方法
let commonUtils = {
  // 定时器存储区
  timers: [],
  
  /*
    设置延时定时器
  */
  wait (time = 1000, name = '') {
    return new Promise((resolve, reject) => {
      try {
        if (name && name !== '') {
          // 删除已有定时器
          commonUtils.clearTimer(name)
          
          // 创建定时器，并存入储存区
          let timer = setTimeout(() => {
            resolve()
          }, time)
          
          const timerObj = {
            name: name,
            index: commonUtils.timers.length,
            type: 'timeout',
            timer
          }
          commonUtils.timers.push(timerObj)
        }
        else {
          // 没有指定名称，创建野定时器
          setTimeout(() => {
            resolve()
          }, time)
        }
      }
      catch (e) {
        reject(e)
      }
    })
  },
  
  interval (time = 1000, name = '', func = () => {}) {
    if (name && name !== '') {
      // 删除已有定时器
      commonUtils.clearTimer(name)
      
      let timer = setInterval(func, time)
      const timerObj = {
        name: name,
        index: commonUtils.timers.length,
        type: 'interval',
        timer
      }
      commonUtils.timers.push(timerObj)
    }
    else {
      // 没有指定名称，创建野定时器
      setInterval(func, time)
    }
  },
  
  // 精确匹配关键字，清除单个定时器
  clearTimer (key = '') {
    let timerObj = commonUtils.timers.find(item => item.name === key)
    if (timerObj) {
      commonUtils.timers.splice(timerObj.index, 1)
      if (timerObj.type === 'timeout') {
        clearTimeout(timerObj.timer)
      }
      else if (timerObj.type === 'interval') {
        clearInterval(timerObj.timer)
      }
    }
  },
  
  // 模糊匹配关键字，批量清除定时器
  clearTimers (key = '') {
    let len = commonUtils.timers.length
    for (let i = 0; i < len; i++) {
      const timerObj = commonUtils.timers[i]
      if (timerObj.name.indexOf(key) >= 0) {
        commonUtils.timers.splice(i, 1)
        if (timerObj.type === 'timeout') {
          clearTimeout(timerObj.timer)
        }
        else if (timerObj.type === 'interval') {
          clearInterval(timerObj.timer)
        }
        i--
        len--
      }
    }
  },
  
  /*
    *********************************
    @section 防抖和节流
    *********************************
  */
  // 节流函数，使得handler函数每次执行都必须有一个间隔wait
  throttle (handler, wait) {
    var lastTime = 0
    
    return function () {
      var nowTime = new Date().getTime()
      
      if (nowTime - lastTime > wait) {
        handler.apply(this, arguments)
        lastTime = nowTime
      }
    }
  },
  
  // 防抖函数，使得handler函数将被延迟执行，无论触发的速度有多快，适用于输入
  debounce (handler, delay) {
    var timer;
 
    return function () {
      var arg = arguments

      clearTimeout(timer)

      timer = setTimeout(() => {
        handler.apply(this, arg)
      }, delay)
    }
  },
}

export default commonUtils